package com.pattern.singleton;

/**
 * Lazy loading  懒汉式
 * 缩小同步块代码块
 */
public class Mgr05 {

    private static Mgr05 INSTANCE;

    private Mgr05(){
    }

    public static Mgr05 getInstance(){
        if (INSTANCE == null) {
            // 此处加同步块 不能解决线程安全问题
            // 原因就是在此处可能存在两个线程同时进入(锁内部代码在增加判断 mgr06)
            synchronized (Mgr05.class){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                INSTANCE = new Mgr05();
            }
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        Long start = System.currentTimeMillis();
        for(int i = 0; i < 100; i++){
            new Thread(() -> {
                System.out.println(Mgr05.getInstance().hashCode());
            }).start();
        }
        Long end = System.currentTimeMillis();
        System.out.println("mill: " + (end - start));
    }
}
